package com.wbtech.cobub;

import java.util.List;

import com.wbtech.cobub.model.Locations;
import com.wbtech.cobub.service.LocationService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class WIFIActivity extends Activity{

	private String wifiMacString = "";
	private String wifiSignalString = "";
	private String ssid = "";
	private String latitude = "";
	private String longitude = "";
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.wifi);
	        
	        
	        RefreshWifiStatus();
	        
	    	TextView cellText = (TextView)findViewById(R.id.textCellInfo);
			cellText.setText("MAC:"+wifiMacString + "\nSignal:"+wifiSignalString + " SSID:"+ssid);
			
			 Button btnSearch = (Button)findViewById(R.id.btnSearch);
		        btnSearch.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
			    		if(wifiMacString.equals(""))
			    		{
			    			Toast.makeText(getApplicationContext(), "当前无WIFI信息", Toast.LENGTH_SHORT).show();
			    			return;
			    		}
			    		
						WSAsyncTask task = new WSAsyncTask();
			    		task.execute();				
					}
				});
		        
		        
		      Button btnMap = (Button)findViewById(R.id.btnViewMap);
		      btnMap.setOnClickListener(new OnClickListener() {					
					public void onClick(View v) {
						if(latitude.equals("")||longitude.equals(""))
						{
							Toast.makeText(getApplicationContext(), "当前无GPS数据", Toast.LENGTH_SHORT).show();
							return;
						}
						Intent mapIntent = new Intent(WIFIActivity.this,MapsActivity.class);
						mapIntent.putExtra("latitude", latitude);
						mapIntent.putExtra("longitude", longitude);
						startActivity(mapIntent);
					}
				});
		}


	 private Dialog BuildMap() {
			LayoutInflater inflater = LayoutInflater.from(this);
			final View mapView = inflater.inflate(
					R.layout.about, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(WIFIActivity.this);			
			builder.setTitle("当前查询位置");
			builder.setView(mapView);
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

				}
			});
			return builder.create();
		}
	 
	private void RefreshWifiStatus() {
		try {
			WifiManager  wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
			
			if(wifiManager == null)
			{
				Toast.makeText(getApplicationContext(), "WIFI未启用", Toast.LENGTH_SHORT).show();
				return;
			}
			
			List<ScanResult> sResults = wifiManager.getScanResults();
			int maxLevel = -10000;
			if(sResults!=null && sResults.size()>0)
			{
				for(int i=0;i<sResults.size();i++)
				{
					ScanResult sr = sResults.get(i);
					if(sr.level>maxLevel)
					{
						maxLevel = sr.level;
						wifiMacString = sr.BSSID;
						wifiSignalString = String.valueOf(sr.level);
						ssid = sr.SSID;
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	    
	 
	 
	 class WSAsyncTask extends AsyncTask
	    {
	    	ProgressDialog dialog = null;

	    	protected Object doInBackground(Object... params)
	    	{
	    		 RefreshWifiStatus();
				Locations loation = LocationService.GetAddressByWIFI(wifiMacString,wifiSignalString,"zh-CN");
				return loation;
	    	}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dialog = new ProgressDialog(WIFIActivity.this);
				dialog.setCancelable(false);
				dialog.setTitle("地址查询...");
				dialog.setMessage("查询中,请稍候...");
				dialog.show();
			}

			@Override
			protected void onPostExecute(Object result) {
				super.onPostExecute(result);
		        setProgressBarIndeterminateVisibility(false);
				dialog.dismiss();
				TextView cellText = (TextView)findViewById(R.id.textCellInfo);
				cellText.setText("MAC:"+wifiMacString + "\nSignal:"+wifiSignalString + " SSID:"+ssid);
				Locations ret = (Locations)result;
				if(ret.getFlag() == null || ret.getMsg() == null)
				{
					Dialog messageDialog = buildMessageDialog(WIFIActivity.this,"查询失败,当前网络较慢或无连接，请稍后重试....");
					messageDialog.show();
				}
				else if(ret.getFlag())
				{
					   ((TextView)findViewById(R.id.textLatitudeValue)).setText(ret.getLatitude());
					   ((TextView)findViewById(R.id.textLongitudeValue)).setText(ret.getLongitude());
					   
					   latitude = ret.getLatitude();
					   longitude = ret.getLongitude();
					       
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
				       ((TextView)findViewById(R.id.textRegionValue)).setText(ret.getRegion());
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCounty());
				       ((TextView)findViewById(R.id.textCitryValue)).setText(ret.getCity());
				       ((TextView)findViewById(R.id.textStreetValue)).setText(ret.getStreet());
				       ((TextView)findViewById(R.id.textStreetNumberValue)).setText(ret.getStreetNumber());
				       ((TextView)findViewById(R.id.textPostalCodeValue)).setText(ret.getPostalcode());
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
				}
				else
				{
					Dialog messageDialog = buildMessageDialog(WIFIActivity.this,ret.getMsg());
					messageDialog.show();
				}
			}
	    }
	  
	  
	 private Dialog buildMessageDialog(Context context,String message) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("Cobub提示");
			builder.setMessage(message);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							setTitle("Cobub提示");
						}
					});
			return builder.create();

		}
	  
	  private Dialog ExitDialog(Context context) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("Cobub提示");
			builder.setMessage("确定退出么?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

						}
					});
			return builder.create();
		}

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				ExitDialog(WIFIActivity.this).show();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
}
